import { config } from "@/utils/uni-config.js";
import { getData, removeData } from "@/utils/auth.js";

let timeout = config.TIMEOUT
const uploadUrl = config.uploadUrl

function tansParams(params) {
  let result = ''
  for (const propName of Object.keys(params)) {
    const value = params[propName]
    var part = encodeURIComponent(propName) + "="
    if (value !== null && value !== "" && typeof (value) !== "undefined") {
      if (typeof value === 'object') {
        for (const key of Object.keys(value)) {
          if (value[key] !== null && value[key] !== "" && typeof (value[key]) !== 'undefined') {
            let params = propName + '[' + key + ']'
            var subPart = encodeURIComponent(params) + "="
            result += subPart + encodeURIComponent(value[key]) + "&"
          }
        }
      } else {
        result += part + encodeURIComponent(value) + "&"
      }
    }
  }
  return result
}

export const upload = (config = {}) => {
  // 是否需要设置 token
  const isToken = (config.headers || {}).isToken === false
  config.header = config.header || {}
  if (getData("access_token") && !isToken) {
    config.header['Authorization'] = 'Bearer ' + getData("access_token")
  }
  // get请求映射params参数
  if (config.params) {
    let url = config.url + '?' + tansParams(config.params)
    url = url.slice(0, -1)
    config.url = url
  }
  console.log('config',config)
  return new Promise((resolve, reject) => {
      uni.uploadFile({
        timeout: config.timeout || timeout,
        url: uploadUrl + config.url,
        filePath: config.filePath,
        name: config.name || 'file',
        header: config.header,
        formData: config.formData,
        success: (res) => {
			
          let result = JSON.parse(res.data)
		  console.log('result',result)
          const code = result.code || 200
          const msg = result.msg
          if (code == 200) {
			  console.log(code == 200)
            resolve(result)
          } else if (code == 401) {
            reject('无效的会话，或者会话已过期，请重新登录。')
          } else if (code == 500) {
			uni.showToast({
				title: msg,
				icon: "none",
				duration: 4000
			})
            reject('500')
          } else if (code != 200) {
            uni.showToast({
            	title: msg,
            	icon: "none",
            	duration: 4000
            })
            reject(code)
          }
        },
        fail: (error) => {
			console.log('error',error)
			uni.showToast({
				title: error.msg || '未知异常',
				icon: "none",
				duration: 4000
			})
          reject(error)
        }
      })
  })
}